package cn.llming.gift.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.StrUtil;
import cn.llming.gift.client.AuthClient;
import cn.llming.gift.domain.Employee;
import cn.llming.gift.domain.LoginUser;
import cn.llming.gift.domain.Tenant;

import cn.llming.gift.exception.ErrorCode;
import cn.llming.gift.exception.LlmingAssert;
import cn.llming.gift.exception.LlmingException;
import cn.llming.gift.mapper.EmployeeMapper;
import cn.llming.gift.mapper.TenantMapper;
import cn.llming.gift.query.TenantQuery;
import cn.llming.gift.service.ITenantService;
import cn.llming.gift.util.AjaxResult;
import cn.llming.gift.util.BaiduAuditUtils;
import cn.llming.gift.util.PageList;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author llming
 * @since 2023-04-24
 */
@Service
public class TenantServiceImpl extends ServiceImpl<TenantMapper, Tenant> implements ITenantService {
    
    @Autowired
    private TenantMapper tenantMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private AuthClient authClient;



    @Override
    public PageList loadPageList(TenantQuery query) {

        Page<Tenant> page = new Page<Tenant>(query.getPage(),query.getRows());
       List<Tenant> tenants= tenantMapper.loadPageList(page,query);
        return new PageList(page.getTotal(), tenants);
    }

    /**
     * 租户入住
     * @param tenant
     */

    @Override
    @Transactional
    public void settledIn(Tenant tenant) {


        valiPrame(tenant);
        //审核
        Boolean auditResult=true;
        String msg="审核通过";
        List<String> strings=new ArrayList<>();
        strings.add(tenant.getCompanyName());
        strings.add(tenant.getAddress());
        strings.add(tenant.getAdmin().getUsername());
        Map<String, Object> map = BaiduAuditUtils.contentCensor(strings, null);
        Boolean success = (Boolean)map.get("success");

        String message =(String)map.get("message");

        LoginUser loginUser=new LoginUser();
        loginUser.setUsername(tenant.getAdmin().getUsername());
        loginUser.setEmail(tenant.getAdmin().getEmail());
        loginUser.setPassword(tenant.getAdmin().getPassword());
        loginUser.setTel(tenant.getAdmin().getTel());

        Employee admin = tenant.getAdmin();
        Integer logState=null;
        Integer adminState=null;
        if(auditResult){
            logState=0;
            adminState=1;

        }else {
            logState=-1;
            adminState=0;

        }
        loginUser.setType(logState);
        //保存登录信息
        AjaxResult ajaxResult = authClient.addOrUpdate(loginUser);

        Long loginId=Long.parseLong(ajaxResult.getResultObj().toString());
        //保存租户

        admin.setLoginId(loginId);
        admin.setRealName(admin.getUsername());
        admin.setTenantId(tenant.getMealId());
        admin.setState(adminState);
        admin.setInputTime(new DateTime());
        //保存管理员
        employeeMapper.insert(admin);

        //保存租户
        tenant.setAdminId(admin.getId());
        tenant.setRegisterTime(new Date());
        tenant.setState(auditResult?1:2);

        tenantMapper.insert(tenant);

        //保存套餐
        tenantMapper.saveTenantAndMeal(tenant.getId(),tenant.getMealId());
        //添加审核日志

       // tenantMapper.insertAuditLog();



        if(auditResult){
            //发送激活邮件
        }else {
            //失败邮件

        }



    }

    private void valiPrame3(Tenant tenant) {
        Employee admin = tenant.getAdmin();
        String address = tenant.getAddress();
        String companyName = tenant.getCompanyName();
        String companyNum = tenant.getCompanyNum();

        String password = admin.getPassword();
        String confirmPassword = admin.getConfirmPassword();


        List<Tenant> tenants = tenantMapper.selectList(new EntityWrapper<Tenant>().eq("company_name", companyName));


        List<Employee> username = employeeMapper.selectList(new EntityWrapper<Employee>().eq("username", admin.getUsername()));

        LlmingAssert.isNotColNull(username, "租户管理员已存在!!");


    }
    private void valiPrame(Tenant tenant) {
        Employee admin = tenant.getAdmin();
        String address = tenant.getAddress();
        String companyName = tenant.getCompanyName();
        String companyNum = tenant.getCompanyNum();
        //非空校验

        LlmingAssert.isBlank(address, ErrorCode.CODE_400);
        LlmingAssert.isBlank(companyName,  ErrorCode.CODE_400);
        LlmingAssert.isBlank(companyNum, ErrorCode.CODE_400);

        String password = admin.getPassword();
        String confirmPassword = admin.getConfirmPassword();

        //两次密码校验
        LlmingAssert.isEqual(password, confirmPassword, ErrorCode.CODE_400_TENANT_ADMIN_PASSWORD_NOT_EQ);

        //租户名不能重复

        List<Tenant> tenants = tenantMapper.selectList(new EntityWrapper<Tenant>().eq("company_name", companyName));

        LlmingAssert.isNotColNull(tenants, ErrorCode.CODE_400_TENANT_EXSIT);

        //管理员不能重复

        List<Employee> username = employeeMapper.selectList(new EntityWrapper<Employee>().eq("username", admin.getUsername()));

        LlmingAssert.isNotColNull(username, ErrorCode.CODE_400_TENANT_ADMIN_EXSIT);


    }

    private void valiPrame1(Tenant tenant) {
        Employee admin = tenant.getAdmin();
        String address = tenant.getAddress();
        String companyName = tenant.getCompanyName();
        String companyNum = tenant.getCompanyNum();
//非空校验
        //两次密码校验

        if(StrUtil.isEmpty(address) || StrUtil.isEmpty(companyName) || StrUtil.isEmpty(companyNum))
            throw new RuntimeException("参数不能为空");
        String password = admin.getPassword();
        String confirmPassword = admin.getConfirmPassword();

        //两次密码校验
        if(!password.equals(confirmPassword))
            throw new RuntimeException("两次密码不一致！");
        //租户名不能重复

        List<Tenant> tenants = tenantMapper.selectList(new EntityWrapper<Tenant>().eq("company_name", companyName));
        if(tenants !=null && tenants.size() >1)
            throw new RuntimeException("租户已存在!!");

        //管理员不能重复

        List<Employee> username = employeeMapper.selectList(new EntityWrapper<Employee>().eq("username", admin.getUsername()));
        if(tenants !=null  && tenants.size() >1)
            throw new RuntimeException("租户管理员已存在!!");


    }
}
